﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace LczWebPart
{
    public class Tools
    {
        public static string GetHtmlTableByDataTable(DataTable dt)
        {
            string strHtmlTable = "<table>$TableHeader$ $TableContent$</table>";
            StringBuilder sbHtmlTableHeader = new StringBuilder();
            StringBuilder sbHtmlTds = new StringBuilder();
            //XmlDocument xml = new XmlDocument();
            //xml.Load(HttpContext.Current.Server.MapPath("~/XmlTemplate/HouseKeeperCustomer.xml"));
            //DataTable dt = DAL.HouseDAL.GetHouseKeeperCustomerInfo(userID);

            string[] strArrayParameter = new string[dt.Columns.Count];//创建替换符数组
            //给数组填值,生成以
            for (int k = 0; k < dt.Columns.Count; k++)
            {
                sbHtmlTableHeader.Append("<td>" + dt.Columns[k].ColumnName.ToString() + "</td>");//添加以字段名为表头名
                strArrayParameter[k] = dt.Columns[k].ColumnName.ToString();
                sbHtmlTds.Append("<td>$" + strArrayParameter[k] + "$</td>");
            }
            strHtmlTable = strHtmlTable.Replace("$TableHeader$", sbHtmlTableHeader.ToString());//将已拼接好的表头放入主模板
            string strHtmlTr = "<tr>$Tds$</tr>";
            strHtmlTr = strHtmlTr.Replace("$Tds$", sbHtmlTds.ToString());//生成带替换符的Tr模板


            StringBuilder sbHtmlTable = new StringBuilder();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strPlacemark = strHtmlTr;
                    for (int j = 0; j < strArrayParameter.Length; j++)
                    {
                        strPlacemark = strPlacemark.Replace("$" + strArrayParameter[j] + "$", dt.Rows[i][strArrayParameter[j]].ToString());
                    }

                    //strPlacemark = strPlacemark.Replace("$ContractNo$", dt.Rows[i]["ContractNo"].ToString());
                    //strPlacemark = strPlacemark.Replace("$CZPrice$", dt.Rows[i]["CZPrice"].ToString());
                    sbHtmlTable.Append(strPlacemark);
                }
                strHtmlTable = strHtmlTable.Replace("$TableContent$", sbHtmlTable.ToString());
            }
            return strHtmlTable;
        }
    }
}
